package com.example.fwcz.util;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Collection;
import java.util.Date;

@Component
public class JwtUtils {
    // --- 生成JWT的工具类 ---
    private static long expireTime;
    private static String secretKey;

    @Value("${token.secretKey}")
    public void setSecretKey(String secretKey){this.secretKey=secretKey;}

    @Value("${token.expireTime}")
    public void setExpireTime(long expireTime){this.expireTime=expireTime;}

    // --- 判断 token 是否存在 ---
    public static boolean judgeTokenIsExist(String token) {
        return token != null && !"".equals(token) && !"null".equals(token);
    }
    // --- 生成 token ---
    public static String generateToken(String subject){
        String jwt = Jwts.builder()
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
        return jwt;
    }
    // --- 生成带角色权限的token ---
    public static String generateToken(String subject, Collection<? extends GrantedAuthority> authorities){
        StringBuilder sb=new StringBuilder();
        for(GrantedAuthority authority:authorities){
            sb.append(authority.getAuthority()).append(",");
        }
        String jwt=Jwts.builder()
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis()+expireTime))
                .signWith(SignatureAlgorithm.HS512,secretKey)
                .compact();
        return jwt;
    }
    // --- 生成自定义过期时间的 token ---
    public static String generateToken(String subject,long expireTime){
        String jwt = Jwts.builder()
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
        return jwt;
    }

    // --- 获取tokenbody同时校验token是否有效 ---
    public static Claims getTokenBody(String token){
        Claims claims=Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token.replace("Bearer","")).getBody();
        return claims;
    }
}
